<script setup lang="ts">
import { ref, reactive } from "vue";
import { creatProject, downloadJmeterPlugins, downloadRecordingPlugins } from "@/api/file";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import uploadIcon from "@iconify-icons/ep/upload-filled";
import downloadIcon from "@iconify-icons/ep/Download";
import { genFileId } from "element-plus";
import { downloadFileWithBuffer } from "@/utils/download";
import type {
  UploadInstance,
  UploadRawFile,
  UploadFile,
  UploadFiles
} from "element-plus";

defineOptions({
  name: "Project"
});
const form = ref({
  projectName: "",
  creater: "",
  fileName: ""
});
const loading = ref(false);
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  projectName: [{ required: true, message: "请输入项目名", trigger: "blur" }],
  creater: [{ required: true, message: "请输入创建人姓名", trigger: "blur" }],
  fileName: [{ required: true, message: "请上传脚本", trigger: "blur" }]
});
const upload = ref<UploadInstance>();

const handleInput = (value: string) => {
  const spaceRegex = /\s/g; // 正则匹配空格
  const specialCharRegex = /[^\w\s\u4e00-\u9fa5]/g;
  if (spaceRegex.test(value)) {
    form.value.projectName = value.replace(spaceRegex, ""); // 移除输入的空格
    ElMessage.error("不允许输入空格");
  } else if (specialCharRegex.test(value)) {
    form.value.projectName = value.replace(specialCharRegex, ""); // 移除输入的特殊字符
    ElMessage.error("不允许输入特殊字符");
  } else {
    form.value.projectName = value;
  }
};
const formChanged = ref(false);

// 生成YAML文件
const run = async () => {
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate();
  try {
    loading.value = true;
    const res = await creatProject(form.value);
    loading.value = false;
    if (res.success) {
      ElMessage.success(res.data);
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    loading.value = false;
    ElMessage.error(error);
  }
};

const handleDownload = async () => {
  try {
    const res = await downloadJmeterPlugins();
    downloadFileWithBuffer(res, 'Jmeter插件.zip');
    ElMessage.success('开始下载');
  } catch (error) {
    ElMessage.error(error);
  }
}

const handleDownloadRecording = async () => {
  try {
    const res = await downloadRecordingPlugins();
    downloadFileWithBuffer(res, '录制插件.zip');
    ElMessage.success('开始下载');
  } catch (error) {
    ElMessage.error(error);
  }
}

const handleSuccess = (
  response: any,
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  console.log("handleSuccess", response, uploadFile, uploadFiles);
  if (response.success) {
    form.value.fileName = response.data.fileName;
    ElMessage.success(response.msg);
  } else {
    upload.value!.clearFiles();
    ElMessage.error(response.msg);
  }
};

const handleExceed = (files: UploadRawFile[]) => {
  upload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload.value!.handleStart(file);
  upload.value!.submit();
};

const hanleReomve = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  console.log("hanleReomve", uploadFile, uploadFiles);
  form.value.fileName = "";
  ElMessage.success("删除成功");
};

const handleError = (
  error: any,
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  console.log("handleError", error, uploadFile, uploadFiles);
  ElMessage.error(error);
};

const handleBeforeUpload = (rawFile: UploadRawFile) => {
  const fileType = rawFile.name.split(".").pop();
  console.log("handleBeforeUpload", rawFile, fileType);
  if (fileType == "zip" || fileType == "rar" || fileType == "7z") {
    return true; // 允许文件上传
  }
  ElMessage.error("只允许上传压缩包(.zip,.rar,.7z)文件");
  return false; // 返回 false 可以阻止文件上传
};
</script>

<template>
  <el-card class="box-card" v-loading="loading" element-loading-text="正在执行...">
    <template #header>
      <div class="card-header">
        <span>创建项目</span>
      </div>
    </template>
    <div>
      <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="项目名" prop="projectName">
          <el-input v-model="form.projectName" placeholder="请输入项目名" clearable @input="handleInput" />
        </el-form-item>
        <el-form-item label="创建人" prop="creater">
          <el-input v-model="form.creater" placeholder="请输入创建人姓名" clearable />
        </el-form-item>
        <el-form-item label="上传脚本" prop="fileName">
          <el-upload ref="upload" class="upload" drag action="/api/file/upload" :limit="1" :on-success="handleSuccess"
            :on-exceed="handleExceed" :on-remove="hanleReomve" :on-error="handleError" :before-upload="handleBeforeUpload"
            accept=".zip,.rar,.7z">
            <div class="el-upload_content">
              <IconifyIconOffline :icon="uploadIcon" style="width: 50px; height: 50px" />
              <div class="el-upload__text">
                拖拽文件到此处或 <em>点击此处上传</em>
              </div>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                tips:<p>1.请上传脚本压缩包(.zip/.rar/.7z)，压缩包内请勿嵌套目录，所有脚本与参数化文件放在同一级目录下；</p>
                <p>2.JMX脚本文件名以TC开头，并与脚本中的事务控制器名一致；</p>
                <p>3.若需要开启资源监控，JMX脚本中需要添加两个PerMon Metrics Collector插件，并分别命名为“Res_CPU”、“Res_Memory”；</p>
                <p>4.引用参数化文件时使用相对引用。</p>
                <div class="flex items-center">
                  <IconifyIconOffline :icon="downloadIcon" />
                  <el-link type="primary" @click="handleDownload">&nbsp点击下载Jmeter插件</el-link>
                </div>
                <div class="flex items-center">
                  <IconifyIconOffline :icon="downloadIcon" />
                  <el-link type="primary" @click="handleDownloadRecording">&nbsp点击下载浏览器录制插件</el-link>
                </div>
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
    </div>
    <div class="form-footer">
      <el-button type="primary" @click="run()">立即创建</el-button>
    </div>
  </el-card>
</template>

<style lang="scss" scoped>
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: 600;
}

.upload {
  width: 100%;
}

.el-upload_content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.form-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
